package com.qd.core.security.handle;

import com.cdqidi.dto.ApiResult;
import com.cdqidi.dto.ApiResultWrapper;
import com.cdqidi.exception.ApiException;
import com.cdqidi.util.ServletUtil;
import com.cdqidi.util.SpringContextHolder;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.qd.common.sys.constant.Constants;
import com.qd.common.sys.domain.login.LoginLogDTO;
import com.qd.common.sys.domain.login.LoginUser;
import com.qd.common.sys.event.LoginUserLogEvent;
import com.qd.system.service.person.AuthTokenService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 自定义退出处理类 返回成功
 *
 * @author sjk
 */
@Configuration
@Slf4j
@RequiredArgsConstructor
public class LogoutSuccessHandlerImpl implements LogoutSuccessHandler {
    private final AuthTokenService tokenService;
    private final ObjectMapper objectMapper;

    /**
     * 退出处理
     */
    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws JsonProcessingException {
        final String token = tokenService.getToken(request);
        if (!StringUtils.hasLength(token)) {
            throw new ApiException("token不能为空");
        }
        final LoginUser loginUser = tokenService.getLoginUser(request);
        if (null == loginUser) {
            throw new ApiException(401, "token失效或者错误");
        } else {
            final String userName = loginUser.getUsername();
            log.info("用户退出userName: " + userName);
            // 删除用户缓存记录
            tokenService.loginOut();
            // 记录用户退出日志
            SpringContextHolder.publishEvent(new LoginUserLogEvent(new LoginLogDTO(loginUser, Constants.LOGOUT, "退出成功")));
        }
        final ApiResultWrapper<String> wrapper = ApiResult.success("退出成功");
        final String json = objectMapper.writeValueAsString(wrapper);
        ServletUtil.renderString(response, json);
    }
}
